package com.jwdf.uda.ui.fragment.user.personal;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.ImageViewState;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.jwdf.uda.R;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.bean.UploadImageResponse;
import com.jwdf.uda.databinding.FragmentSetCoverBinding;
import com.jwdf.uda.event.CoverEvent;
import com.jwdf.uda.event.ImageSelectorEvent;
import com.jwdf.uda.event.IndividualEvent;
import com.jwdf.uda.http.AHttpService;
import com.jwdf.uda.http.HttpHelper;
import com.jwdf.uda.http.action.UploadImageAction;
import com.jwdf.uda.http.action.UserUpdateInfoAction;
import com.jwdf.uda.photopicker.PhotoPickerActivity;
import com.jwdf.uda.runtime.PermissionRequest;
import com.jwdf.uda.runtime.RuntimePermission;
import com.jwdf.uda.ui.activity.CoverActivity;
import com.jwdf.uda.ui.activity.PhotoActivity;
import com.jwdf.uda.ui.fragment.base.BaseFragment;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.view.dialog.AlertDialog;
import java.io.File;
import java.util.ArrayList;
import retrofit2.Response;

/**
 * Created by Administrator on 2016/9/26.
 */
public class SetCoverFragment extends BaseFragment {
    private FragmentSetCoverBinding mDataBinding;
    private Uri imageUri;
    PbBean.PbResUserUpdateInfo info;
    private static final String EXTRA_PHOTO = "photo";
    public static final int REQ_AVATAR_CHANGE = 0x100;
    public static final int REQ_AVATAR_CROP = 0x101;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mDataBinding = FragmentSetCoverBinding.inflate(inflater, container, false);
        initViews();
        return mDataBinding.getRoot();
    }

    private void initViews() {
        checkPermission();
//        ImageLoader.getInstance().displayImage(getArguments().getString(EXTRA_PHOTO), mDataBinding.ivAvatar);
        mDataBinding.ivAvatar.setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_CUSTOM);
        mDataBinding.ivAvatar.setMinScale(1.0f);
        Glide.with(getContext())
                .load(getArguments().getString(EXTRA_PHOTO)).downloadOnly(new SimpleTarget<File>() {
            @Override
            public void onResourceReady(File resource, GlideAnimation<? super File> glideAnimation) {
                mDataBinding.ivAvatar.setImage(ImageSource.uri(Uri.fromFile(resource)), new ImageViewState(1.0f, new PointF(0, 0), 0));
            }
        });

        mDataBinding.ivAvatar.setTag(R.id.tag_url, getArguments().getString(EXTRA_PHOTO));
        mDataBinding.ivAvatar.setOnClickListener(createOnClickListener());
        mDataBinding.rlChange.setOnClickListener(createOnClickListener());
        mDataBinding.rlCover.setOnClickListener(createOnClickListener());
    }

    @PermissionRequest(100)
    private void checkPermission() {
        String perms[] = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (!RuntimePermission.hasPermissions(getContext(), perms)) {
            RuntimePermission.requestPermissions(this, getString(R.string.app_name),
                    100, perms);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBusUtil.registerEvent(this);
    }

    @Override
    public void onDestroy() {
        EventBusUtil.unregisterEvent(this);
        super.onDestroy();
    }

    public void onEvent(ImageSelectorEvent event) {
        if (ImageSelectorEvent.EVENT_ADD == event.getType() && event.getCode() == REQ_AVATAR_CHANGE) {
//            startPhotoZoom(Uri.parse(event.getImages().get(0)));
//                ImageLoader.getInstance().displayImage(event.getImages().get(0), mDataBinding.ivAvatar);
            Glide.with(getContext())
                    .load(event.getImages().get(0)).downloadOnly(new SimpleTarget<File>() {
                @Override
                public void onResourceReady(File resource, GlideAnimation<? super File> glideAnimation) {
                    mDataBinding.ivAvatar.setImage(ImageSource.uri(Uri.fromFile(resource)), new ImageViewState(1.0f, new PointF(0, 0), 0));
                }
            });
            mDataBinding.ivAvatar.setTag(R.id.tag_url, event.getImages().get(0));
            doUploadImageAction(event.getImages().get(0));
        }
    }

    public void onEvent(CoverEvent event) {
        switch (event.getEvent()) {
            case CoverEvent.EVENT_COVER:
                if (event.cover != null) {
//                    startPhotoZoom(Uri.parse(event.cover));
//                    ImageLoader.getInstance().displayImage(event.cover, mDataBinding.ivAvatar);
                    Glide.with(getContext())
                            .load(event.cover).downloadOnly(new SimpleTarget<File>() {
                        @Override
                        public void onResourceReady(File resource, GlideAnimation<? super File> glideAnimation) {
                            mDataBinding.ivAvatar.setImage(ImageSource.uri(Uri.fromFile(resource)), new ImageViewState(1.0f, new PointF(0, 0), 0));
                        }
                    });
                    mDataBinding.ivAvatar.setTag(R.id.tag_url, event.cover);
                    doUploadImageAction(event.cover);
                }
                break;
//            case CoverEvent.EVENT_COVER_CLOSE:
//                IndividualEvent individualEvent = new IndividualEvent(IndividualEvent.USER_AVATAR_EVENT);
//                if(info !=null) {
//                    individualEvent.userInfo = info.getUserInfo();
//                }
//                EventBusUtil.post(individualEvent);
//                break;
        }

    }

    public void startPhotoZoom(Uri uri) {
        imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/avatartemp" + System.currentTimeMillis() + ".jpg"));
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "false");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//图像输出
        intent.putExtra("outputFormat",
                Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("return-data", false);//回调方法data.getExtras().getParcelable("data")返回数据为空
        startActivityForResult(intent, REQ_AVATAR_CROP);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 截图后返回
        if (requestCode == REQ_AVATAR_CROP && data != null) {
//            ImageLoader.getInstance().displayImage(imageUri.toString(), mDataBinding.ivAvatar);
            Glide.with(getContext())
                    .load(imageUri.toString()).downloadOnly(new SimpleTarget<File>() {
                @Override
                public void onResourceReady(File resource, GlideAnimation<? super File> glideAnimation) {
                    mDataBinding.ivAvatar.setImage(ImageSource.uri(Uri.fromFile(resource)), new ImageViewState(1.0f, new PointF(0, 0), 0));
                }
            });
            mDataBinding.ivAvatar.setTag(R.id.tag_url, imageUri.toString());
            mDataBinding.rlCover.setTag(R.id.tag_url, imageUri.toString());
            doUploadImageAction(imageUri.toString());
        }
    }

    private void doUploadImageAction(final String image) {
        showProgressDialog();
        UploadImageAction action = new UploadImageAction(getContext(), image,false);
        onNewRequestCall(action.request(new UploadImageAction.IResCallback<String>() {
            @Override
            public void onCallback(int resultCode, UploadImageResponse response) {
                if (getView() != null) {
                    if (HttpHelper.showError(getContext(), resultCode, response, getString(R.string.error_operation))) {
                        cancelRequest();
                        closeProgressDialog();
                        return;
                    }
                    updateUserInfo(response.getToken());
                }
            }
        }));
    }

    private void updateUserInfo(String imageToken) {
        onNewRequestCall(UserUpdateInfoAction.newInstance(imageToken, getContext()).request(new AHttpService.IResCallback<PbBean.PbResUserUpdateInfo>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResUserUpdateInfo> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (getView() != null) {
                    closeProgressDialog();
                    if (HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                        return;
                    }
                    info = response.body();
                    IndividualEvent individualEvent = new IndividualEvent(IndividualEvent.USER_AVATAR_EVENT);
                    individualEvent.userInfo = info.getUserInfo();
                    EventBusUtil.post(individualEvent);
                }
            }
        }));
    }

    private void showAlertNotice() {
        final AlertDialog alertDialog = new AlertDialog(getContext(), getContext().getString(R.string.permission_denied_msg), new AlertDialog.CallbackListener() {
            @Override
            public void clickYes() {

            }
        });
        alertDialog.show();
    }

    private View.OnClickListener createOnClickListener() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.iv_avatar:
                        SubsamplingScaleImageView imageView = (SubsamplingScaleImageView) v;
                        final ArrayList<String> urls = new ArrayList<>();
                        urls.add((String) imageView.getTag(R.id.tag_url));
                        PhotoActivity.start(v.getContext(), urls, 0);
                        break;
                    case R.id.rl_change:
                        String perms[] = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
                        if (RuntimePermission.hasPermissions(getContext(), perms)) {
                            PhotoPickerActivity.startActivity(getContext(), REQ_AVATAR_CHANGE, new ArrayList<String>(), 1);
                        } else {
                            showAlertNotice();
                        }
                        break;
                    case R.id.rl_cover:
                        CoverActivity.start(getContext());
                        break;
                }
            }
        };
    }
}

